package com.anpy.bill.service.impl;

import com.anpy.bill.entity.ClassifyEntity;
import com.anpy.bill.entity.ClassifyResultEntity;
import com.anpy.bill.mapper.BillClassifyMapper;
import com.anpy.bill.mapper.BillMapper;
import com.anpy.bill.service.BillClassifyService;
import com.anpy.common.service.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("billClassifyServiceImpl")
public class BillClassifyServiceImpl extends BaseServiceImpl<BillClassifyMapper, ClassifyEntity> implements BillClassifyService {

    @Resource
    private BillMapper billMapper;

    @Override
    public boolean saveClassify(String classifyName) {
        LambdaQueryWrapper<ClassifyEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassifyEntity::getName, classifyName);
        ClassifyEntity entity = this.getOne(wrapper);
        if (entity == null) {
            entity = new ClassifyEntity();
            entity.setName(classifyName);
            return this.save(entity);
        }
        return false;
    }

    @Override
    public List<ClassifyEntity> classifyList() {
        return this.list();

    }

    @Override
    public List<Map<String,Object>> queryClassifyList(Integer userId) {
        List<ClassifyResultEntity> classifyResultEntities = billMapper.queryClassifyList();
        Map<String, List<ClassifyResultEntity>> collect = classifyResultEntities.stream().collect(Collectors.groupingBy(ClassifyResultEntity::getClassifyName));

        List<Map<String,Object>> list = new ArrayList<>();
        for (Map.Entry<String, List<ClassifyResultEntity>> entry : collect.entrySet()) {
            Map<String,Object> map = new HashMap<>();
            String key = entry.getKey();
            List<ClassifyResultEntity> value = entry.getValue();
            map.put("classifyName",key);
            if(value.size()>0){
                map.put("classifyId",value.get(0).getClassifyId());
            }
            map.put("list",value);
            list.add(map);
        }
        return list;
    }

}
